//
//  HttpRequest.swift
//  图片缓存
//
//  Created by emma on 2024/4/20.
//

import UIKit

class HttpRequest: NSObject {
    
    static let shared = HttpRequest()
    private var tasks = [URLSessionDataTask]()
    
    override init() {
        super.init()
        
        NetworkManager.shared.networkMonitoring {
            for task in self.tasks {
                task.resume()
            }
            self.tasks.removeAll()
        }
    }
    
    //MARK: - 下载文件
    func download(_ urlString: String,success: @escaping ((_ data: Data) -> ()),failure: @escaping ((_ error: Error?) -> ())) {
        MyLog("-----请求接口:\(urlString)-----")
        let url = URL(string: urlString)
        guard let url = url else { return }
        var request = URLRequest(url: url)
        request.timeoutInterval = 30
        
        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, respond, error) in
            MyLog(data)
            DispatchQueue.main.async {
                if let data = data {
                    success(data)
                }else {
                    failure(error)
                }
            }
        }
        if NetworkManager.shared.isReachable {
            task.resume()
        }else {
            tasks.append(task)
        }
    }
}


import Network
 
class NetworkManager {
    static let shared = NetworkManager()
    
    var isReachable: Bool {
        return NWPathMonitor().currentPath.status == .satisfied
    }
 
    func networkMonitoring(callback: (()->Void)?) {
        let monitor = NWPathMonitor()
        let queue = DispatchQueue(label: "NetworkMonitor")
        monitor.start(queue: queue)
 
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                // 网络恢复，重新请求数据
                callback?()
            }
        }
    }
}
